package com.vf.admin.utils.sendsms.wwlt;

import java.io.IOException;
import java.net.URISyntaxException;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.vf.admin.utils.sendsms.wwlt.httpclient.*;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SendSmsSender extends SmsBase{
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	private String url = "https://api.51welink.com/EncryptionSubmit/SendSms.ashx";
	private static String accountId = "dlzhiyu00";//提交账户
	private static String password = "Asd112233";
	private String productId = "1012818";//产品编码，供应商提供

	public static SendSmsSender getInstance(){
		return new SendSmsSender();
	}
	public SendSmsSender() {
		super(accountId, password, new DefaultHttpClient());
	}
	
	public SendSmsResult send(String phone, String code, String packageName) throws HttpException, JSONException, IOException{
		if(ObjectUtil.isEmpty(packageName)){
			packageName = "popose";
		}
		String smsContent = "【"+packageName+"】您的验证码"+code+"，请勿向任何人提供您收到的短信验证码！"; // 注意测试时，也请带上公司简称或网站签名，发送正规内容短信。千万不要发送无意义的内容：例如 测一下、您好。否则可能会收不到

		long Random = SmsSenderUtil.getRandom();
		long Timestamp = SmsSenderUtil.getCurrentTime();
		JSONObject body = new JSONObject()
				.put("AccountId", accountId)
                .put("ProductId", productId)
                .put("PhoneNos", phone)
                .put("Content", smsContent)
                .put("AccessKey", SmsSenderUtil.calcSendSmsSign(accountId, phone, password, Random, Timestamp))
                .put("Timestamp", Timestamp)
                .put("Random", Random);
//                .put("OutId", SmsSenderUtil.isNotEmpty(OutId) ? OutId : "")
//                .put("SendTime", SmsSenderUtil.isNotEmpty(SendTime) ? SendTime : "")
		System.out.println(JSON.toJSON(body.toString()));
		logger.info("短信请求："+JSON.toJSON(body.toString()));
		HttpRequest request = new HttpRequest(HttpMethod.POST, url)
				.addHeader("Content-Type", "application/json")
                .setConnectTimeout(30 * 1000)
                .setRequestTimeout(30 * 1000)
                .setBody(body.toString());
		try {
			HttpResponse response = httpClient.fetch(request);
			handleError(response);
			SendSmsResult result = (new SendSmsResult()).parseFromHttpResponse(response);
			System.out.println("短信结果："+JSON.toJSON(result));
			logger.info("短信结果："+JSON.toJSON(result));
			return result;
		} catch (URISyntaxException e) {
			e.printStackTrace();
			logger.info("短信错误："+JSON.toJSON(e));
			throw new RuntimeException("API url has been modified, current url: " + url);
		}
	}
}
